<template>
  <div class="exam-questions-container">
    <!-- 考试基本信息 -->
    <a-card title="考试基本信息" style="margin-bottom: 20px">
      <a-descriptions bordered :column="2">
        <template v-if="examInfo.id">
          <a-descriptions-item label="考试名称">{{
            examInfo.name
          }}</a-descriptions-item>
          <a-descriptions-item label="考试类型">
            <a-tag :color="getExamTypeColor(examInfo.type)">
              {{ getExamTypeText(examInfo.type) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="考试班级">{{
            examInfo.class_name
          }}</a-descriptions-item>
          <a-descriptions-item label="考试日期">{{
            examInfo.date
          }}</a-descriptions-item>
          <a-descriptions-item label="总分"
            >{{ examInfo.total_score }}分</a-descriptions-item
          >
          <a-descriptions-item label="状态">
            <a-tag :color="getStatusColor(examInfo.state_del)">
              {{ getStatusText(examInfo.state_del) }}
            </a-tag>
          </a-descriptions-item>
        </template>
        <template v-else>
          <a-descriptions-item label="考试选择" :span="2">
            <a-select
              v-model:value="selectedExamId"
              placeholder="请选择考试"
              style="width: 300px"
              @change="handleExamChange"
            >
              <a-select-option
                v-for="exam in allExams"
                :key="exam.id"
                :value="exam.id"
              >
                {{ exam.name }}
              </a-select-option>
            </a-select>
          </a-descriptions-item>
        </template>
      </a-descriptions>
    </a-card>

    <!-- 题目管理 -->
    <a-card title="考试题目管理" v-if="examInfo.id">
      <template #extra>
        <a-button
          type="primary"
          @click="showBatchAddModal"
          :disabled="examInfo.state_del !== 0"
        >
          <plus-outlined />
          批量添加
        </a-button>
      </template>

      <!-- 题目列表 -->
      <a-table
        :dataSource="questions"
        :columns="questionColumns"
        :pagination="false"
        rowKey="question_id"
        bordered
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex === 'question_order'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'question_type'">
            <a-tag :color="getQuestionTypeColor(record.question_type)">
              {{ getQuestionTypeText(record.question_type) }}
            </a-tag>
          </template>
          <template v-if="column.dataIndex === 'correct_answer'">
            <span
              >{{ record.correct_answer
              }}{{
                record.correct_option ? "--" + record.correct_option : ""
              }}</span
            >
          </template>
          <template v-if="column.dataIndex === 'options' && record.options">
            <div v-for="(option, idx) in JSON.parse(record.options)" :key="idx">
              {{ String.fromCharCode(65 + idx) }}. {{ option }}
            </div>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-button
              type="link"
              size="small"
              @click="editQuestion(record)"
              :disabled="examInfo.state_del !== 0"
            >
              编辑
            </a-button>
            <a-popconfirm
              title="确定要删除此题吗？"
              @confirm="deleteQuestion(record.question_id)"
            >
              <a-button
                type="link"
                size="small"
                danger
                :disabled="examInfo.state_del !== 0"
              >
                删除
              </a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>

      <!-- 总分统计 -->
      <div style="margin-top: 20px; text-align: right; font-weight: bold">
        当前总分: {{ totalScore }}分
      </div>
    </a-card>

    <!-- 批量添加题目模态框 -->
    <a-modal
      v-model:visible="batchModalVisible"
      title="批量添加题目"
      width="800px"
      @ok="handleBatchAdd"
      @cancel="resetBatchForm"
      :confirmLoading="batchLoading"
    >
      <a-form layout="vertical">
        <a-form-item label="题目类型">
          <a-select
            v-model:value="batchQuestionType"
            style="width: 200px"
            @change="handleBatchTypeChange"
          >
            <!-- 1: "选择题",
            2: "简答题",
            3: "填空题", -->
            <a-select-option value="1">选择题</a-select-option>
            <a-select-option value="2">简答题</a-select-option>
            <a-select-option value="3">填空题</a-select-option>
          </a-select>
        </a-form-item>

        <a-table
          :dataSource="batchQuestions"
          :columns="batchColumns"
          :pagination="false"
          bordered
        >
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.dataIndex === 'question_order'">
              {{ index + 1 }}
            </template>
            <template v-if="column.dataIndex === 'question_text'">
              <a-textarea
                v-model:value="record.question_text"
                placeholder="请输入题目内容"
                :rows="2"
              />
            </template>
            <template v-if="column.dataIndex === 'score'">
              <a-input-number
                v-model:value="record.score"
                :min="1"
                :max="100"
                style="width: 100%"
              />
            </template>
            <template v-if="column.dataIndex === 'options' && hasOptions">
              <div v-for="(option, idx) in record.options" :key="idx">
                <a-input
                  v-model:value="record.options[idx]"
                  :placeholder="`选项 ${String.fromCharCode(65 + idx)}`"
                  style="margin-bottom: 5px"
                />
              </div>
              <a-button
                type="dashed"
                size="small"
                @click="addOption(record)"
                v-if="record.options.length < 6"
              >
                <plus-outlined /> 添加选项
              </a-button>
            </template>
            <template v-if="column.dataIndex === 'correct_answer'">
              <template v-if="hasOptions">
                <!-- <a-select
                    v-model:value="record.correct_answer"
                    style="width: 100%"
                    mode="1"
                    v-if="batchQuestionType === '1'"
                  >
                    <a-select-option
                      v-for="(option, idx) in record.options"
                      :key="idx"
                      :value="String.fromCharCode(65 + idx)"
                    >
                      {{ String.fromCharCode(65 + idx) }}
                    </a-select-option>
                  </a-select> -->
                <a-select
                  v-model:value="record.correct_answer"
                  style="width: 100%"
                  v-if="batchQuestionType === '1'"
                >
                  <a-select-option
                    v-for="(option, idx) in record.options"
                    :key="idx"
                    :value="String.fromCharCode(65 + idx)"
                  >
                    {{ String.fromCharCode(65 + idx) }}
                  </a-select-option>
                </a-select>
              </template>
              <a-textarea
                v-model:value="record.correct_answer"
                v-else-if="
                  batchQuestionType === '2' || batchQuestionType === '3'
                "
                :rows="2"
                placeholder="请输入正确答案"
              />
            </template>
            <template v-if="column.dataIndex === 'action'">
              <a-button
                type="link"
                danger
                size="small"
                @click="removeBatchQuestion(index)"
              >
                删除
              </a-button>
            </template>
          </template>
        </a-table>

        <div style="margin-top: 10px; text-align: center">
          <a-button type="dashed" @click="addBatchQuestion">
            <plus-outlined /> 添加题目
          </a-button>
        </div>
      </a-form>
    </a-modal>

    <!-- 编辑题目模态框 -->
    <a-modal
      v-model:visible="editModalVisible"
      :title="`编辑题目 (${currentQuestion?.question_order})`"
      @ok="handleEditQuestion"
      @cancel="resetEditForm"
      :confirmLoading="editing"
    >
      <a-form :model="editForm" layout="vertical">
        <a-form-item label="题目类型">
          <a-tag :color="getQuestionTypeColor(currentQuestion?.question_type)">
            {{ getQuestionTypeText(currentQuestion?.question_type) }}
          </a-tag>
        </a-form-item>
        <a-form-item label="题目内容" required>
          <a-textarea
            v-model:value="editForm.question_text"
            :rows="3"
            placeholder="请输入题目内容"
          />
        </a-form-item>
        <a-form-item label="分数" required>
          <a-input-number
            v-model:value="editForm.score"
            :min="1"
            :max="100"
            style="width: 100%"
          />
        </a-form-item>
        <template v-if="hasEditOptions">
          <a-form-item label="选项">
            <div v-for="(option, idx) in editForm.options" :key="idx">
              <a-input
                v-model:value="editForm.options[idx]"
                :placeholder="`选项 ${String.fromCharCode(65 + idx)}`"
                style="margin-bottom: 5px"
              />
            </div>
            <a-button
              type="dashed"
              size="small"
              @click="addEditOption"
              v-if="editForm.options.length < 6"
            >
              <plus-outlined /> 添加选项
            </a-button>
          </a-form-item>
          <a-form-item label="正确答案" required>
            <a-select
              v-model:value="editForm.correct_answer"
              style="width: 100%"
              :mode="
                currentQuestion?.question_type === 'multiple'
                  ? 'multiple'
                  : undefined
              "
            >
              <a-select-option
                v-for="(option, idx) in editForm.options"
                :key="idx"
                :value="String.fromCharCode(65 + idx)"
              >
                {{ String.fromCharCode(65 + idx) }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </template>
        <template v-else>
          <a-form-item label="正确答案" required>
            <a-textarea
              v-model:value="editForm.correct_answer"
              :rows="2"
              placeholder="请输入正确答案"
            />
          </a-form-item>
        </template>
      </a-form>
    </a-modal>
  </div>
</template>
  
  <script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from "vue";
import { useRoute } from "vue-router";
import { message } from "ant-design-vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import http from "../routerutils/http";

interface ExamInfo {
  id: number;
  name: string;
  type: string;
  date: string;
  class_id: number;
  class_name: string;
  total_score: number;
  average_score: number;
  student_count: number;
  status: number;
  state_del?: number;
}

interface Question {
  question_id: number;
  exam_id: number;
  question_type: string;
  question_text: string;
  question_order: number;
  score: number;
  options: string | null;
  correct_answer: string;
}

interface BatchQuestion {
  question_type: string;
  question_text: string;
  question_order: number;
  score: number;
  options: string[];
  correct_answer: string;
}

interface EditForm {
  question_text: string;
  score: number;
  options: string[];
  correct_answer: string;
}

const route = useRoute();
const selectedExamId = ref<number | null>(null);
const allExams = ref<ExamInfo[]>([]);

// 考试信息
const examInfo = ref<ExamInfo>({
  id: 0,
  name: "",
  type: "",
  date: "",
  class_id: 0,
  class_name: "",
  total_score: 0,
  average_score: 0,
  student_count: 0,
  status: 0,
  state_del: 0,
});

// 题目列表
const questions = ref<Question[]>([]);
const loading = ref(false);

// 题目表格列
const questionColumns = [
  {
    title: "题号",
    dataIndex: "question_order",
    width: 60,
  },
  {
    title: "题型",
    dataIndex: "question_type",
    width: 100,
  },
  {
    title: "题目内容",
    dataIndex: "question_text",
    width: 200,
  },
  {
    title: "选项",
    dataIndex: "options",
    width: 100,
  },
  {
    title: "分数",
    dataIndex: "score",
    width: 80,
  },
  {
    title: "正确答案",
    dataIndex: "correct_answer",
    width: 180,
  },
  {
    title: "操作",
    dataIndex: "action",
    width: 150,
  },
];

// 批量添加相关
const batchModalVisible = ref(false);
const batchLoading = ref(false);
const batchQuestionType = ref("1");
const batchQuestions = ref<BatchQuestion[]>([]);

const hasOptions = computed(() => {
  return ["1", "multiple"].includes(batchQuestionType.value);
});

const batchColumns = [
  {
    title: "序号",
    dataIndex: "question_order",
    width: 60,
  },
  {
    title: "题目内容",
    dataIndex: "question_text",
  },
  {
    title: "分数",
    dataIndex: "score",
    width: 100,
  },
  {
    title: "选项",
    dataIndex: "options",
    width: 200,
    vIf: hasOptions,
  },
  {
    title: "正确答案",
    dataIndex: "correct_answer",
    width: 150,
  },
  {
    title: "操作",
    dataIndex: "action",
    width: 80,
  },
];

const select_value = ref()

// 编辑相关
const editModalVisible = ref(false);
const editing = ref(false);
const currentQuestion = ref<Question | null>(null);
const editForm = reactive<EditForm>({
  question_text: "",
  score: 0,
  options: [],
  correct_answer: "",
});

// 选择题答案
// const Select_answer = (e: any, v: any) => {
//   const option_srr = ['A','B','C','D','E','F'];
//   const value_index = option_srr.findIndex(option => option === v);
//   select_value.value = e[value_index]
//   console.log(value_index,e[value_index]); // 这会输出 v 在数组中的索引（如果存在）
//   console.log(e, v);
// };

const hasEditOptions = computed(() => {
  return (
    currentQuestion.value?.question_type === "1" ||
    currentQuestion.value?.question_type === "multiple"
  );
});

// 总分计算
const totalScore = computed(() => {
  return questions.value.reduce((sum, q) => sum + q.score, 0);
});

// 获取所有考试列表
const fetchAllExams = async () => {
  try {
    const response = await http.get("/api/students/all_exams");
    allExams.value = response.data.results;

    // 如果路由中有examId参数，则自动选择该考试
    if (route.params.id) {
      const examId = Number(route.params.id);
      const exam = allExams.value.find((e) => e.id === examId);
      if (exam) {
        selectedExamId.value = examId;
        handleExamChange(examId);
      }
    }
  } catch (error) {
    console.error("获取考试列表失败:", error);
    message.error("获取考试列表失败");
  }
};

// 获取考试信息
const fetchExamInfo = async (examId: number) => {
  try {
    const response = await http.get(`/api/teacher/exams/${examId}`);
    console.log("考试题目信息：",response)
    examInfo.value = response.data.data;
  } catch (error) {
    console.error("获取考试信息失败:", error);
    message.error("获取考试信息失败");
  }
};

// 获取题目列表
const fetchQuestions = async (examId: number) => {
  try {
    loading.value = true;
    const response = await http.get(`/api/teacher/exams/${examId}`);
    questions.value = response.data.data.questions;
  } catch (error) {
    console.error("获取题目列表失败:", error);
    message.error("获取题目列表失败");
  } finally {
    loading.value = false;
  }
};

// 处理考试选择变化
const handleExamChange = async (examId: number) => {
  if (!examId) return;

  try {
    await Promise.all([fetchExamInfo(examId), fetchQuestions(examId)]);
  } catch (error) {
    console.error("加载考试数据失败:", error);
    message.error("加载考试数据失败");
  }
};

// 显示批量添加模态框
const showBatchAddModal = () => {
  batchModalVisible.value = true;
  addBatchQuestion();
};

// 批量添加题目类型变化
const handleBatchTypeChange = () => {
  batchQuestions.value = batchQuestions.value.map((q) => ({
    ...q,
    question_type: batchQuestionType.value,
    options:
      batchQuestionType.value === "1" || batchQuestionType.value === "multiple"
        ? ["", "", "", ""]
        : [],
    correct_answer: "",
  }));
};

// 添加批量题目
const addBatchQuestion = () => {
  // options: "[\"废人\",\"热热\",\"俄文\",\"微官网\"]"
  batchQuestions.value.push({
    question_type: batchQuestionType.value,
    question_text: "",
    question_order: batchQuestions.value.length + 1,
    score: 5,
    options: hasOptions.value ? ["", "", "", ""] : [],
    correct_answer: "",
  });
};

// 添加选项
const addOption = (question: BatchQuestion) => {
  question.options.push("");
};

// 删除批量题目
const removeBatchQuestion = (index: number) => {
  batchQuestions.value.splice(index, 1);
  // 重新排序
  batchQuestions.value = batchQuestions.value.map((q, idx) => ({
    ...q,
    question_order: idx + 1,
  }));
};

// 处理批量添加
const handleBatchAdd = async () => {
  try {
    batchLoading.value = true;

    // 验证数据
    for (const q of batchQuestions.value) {
      if (!q.question_text.trim()) {
        message.error("请填写所有题目的内容");
        return;
      }
      if (q.score <= 0) {
        message.error("分数必须大于0");
        return;
      }
      if (hasOptions.value && q.options.some((opt) => !opt.trim())) {
        message.error("请填写所有选项内容");
        return;
      }
      if (!q.correct_answer) {
        message.error("请设置正确答案");
        return;
      }
    }

    const payload = {
      questions: batchQuestions.value.map((q) => ({
        ...q,
        // options: hasOptions.value ? JSON.stringify(q.options) : null,
      })),
    };

    await http.post(
      `/api/teacher/exams/${examInfo.value.id}/questions/batch`,
      payload
    );
    message.success("批量添加题目成功");
    batchModalVisible.value = false;
    fetchQuestions(examInfo.value.id);
  } catch (error) {
    console.error("批量添加题目失败:", error);
    message.error("批量添加题目失败");
  } finally {
    batchLoading.value = false;
  }
};

// 重置批量表单
const resetBatchForm = () => {
  batchQuestions.value = [];
  batchQuestionType.value = "1";
};

// 编辑题目
const editQuestion = (question: Question) => {
  currentQuestion.value = question;
  editForm.question_text = question.question_text;
  editForm.score = question.score;
  editForm.correct_answer = question.correct_answer;
  editForm.options = question.options ? JSON.parse(question.options) : [];
  editModalVisible.value = true;
};

// 添加编辑选项
const addEditOption = () => {
  editForm.options.push("");
};

// 处理编辑题目
const handleEditQuestion = async () => {
  try {
    editing.value = true;

    if (!currentQuestion.value) return;

    // 验证数据
    if (!editForm.question_text.trim()) {
      message.error("请填写题目内容");
      return;
    }
    if (editForm.score <= 0) {
      message.error("分数必须大于0");
      return;
    }
    if (hasEditOptions.value && editForm.options.some((opt) => !opt.trim())) {
      message.error("请填写所有选项内容");
      return;
    }
    if (!editForm.correct_answer) {
      message.error("请设置正确答案");
      return;
    }

    const payload = {
      question_text: editForm.question_text,
      score: editForm.score,
      options: hasEditOptions.value ? JSON.stringify(editForm.options) : null,
      correct_answer: editForm.correct_answer,
    };

    await http.put(
      `/api/teacher/exams/${examInfo.value.id}/questions/${currentQuestion.value.question_id}`,
      payload
    );
    message.success("修改题目成功");
    editModalVisible.value = false;
    fetchQuestions(examInfo.value.id);
  } catch (error) {
    console.error("修改题目失败:", error);
    message.error("修改题目失败");
  } finally {
    editing.value = false;
  }
};

// 重置编辑表单
const resetEditForm = () => {
  editForm.question_text = "";
  editForm.score = 0;
  editForm.options = [];
  editForm.correct_answer = "";
  currentQuestion.value = null;
};

// 删除题目
const deleteQuestion = async (questionId: number) => {
  try {
    await http.delete(`/api/teacher/questions/${questionId}`);
    message.success("删除题目成功");
    fetchQuestions(examInfo.value.id);
  } catch (error) {
    console.error("删除题目失败:", error);
    message.error("删除题目失败");
  }
};

// 获取考试类型文本
const getExamTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    // 考试类型： 1 周考；0 月考；2 年考
    1: "周考",
    0: "月考",
    2: "年考",
  };
  return typeMap[type] || type;
};

// 获取考试类型颜色
const getExamTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    1: "blue",
    0: "orange",
    2: "red",
  };
  return colorMap[type] || "default";
};

// 获取状态文本
const getStatusText = (status: any) => {
  const statusMap = ["进行中", "已结束"];
  return statusMap[status] || "未知";
};

// 获取状态颜色
const getStatusColor = (status: any) => {
  const colorMap = ["orange", "green"];
  return colorMap[status] || "default";
};

// 获取题目类型文本
const getQuestionTypeText = (type?: string) => {
  if (!type) return "";
  const typeMap: Record<string, string> = {
    // 1-选择题, 2-简答题，3-填空题
    1: "选择题",
    2: "简答题",
    3: "填空题",
  };
  return typeMap[type] || type;
};

// 获取题目类型颜色
const getQuestionTypeColor = (type?: string) => {
  if (!type) return "";
  const colorMap: Record<string, string> = {
    1: "blue",
    2: "geekblue",
    3: "green",
  };
  return colorMap[type] || "default";
};

onMounted(() => {
  fetchAllExams();
});
</script>
  
  <style scoped>
.exam-questions-container {
  padding: 20px;
}

:deep(.ant-descriptions-item-label) {
  width: 120px;
  font-weight: bold;
}

:deep(.ant-table) {
  margin-top: 16px;
}
</style>